﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.Services;
using DreamBuilder.Core.Container;

namespace Web.WebDoc
{
    /// <summary>
    /// 备注：文件下载
    /// 时间：2013年4月4日 21:04:16
    /// </summary>
    public class FileDownloadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string attachmentID = context.Request.QueryString["AttachmentID"];
                string DBHelperString = context.Request.QueryString["AttachmentDBHelperString"];

                if (string.IsNullOrEmpty(DBHelperString) || string.IsNullOrEmpty(attachmentID))
                {
                    throw new Exception("参数AttachmentDBHelperString或者AttachmentID不能为空");
                }

                IAttachmentService oIAttachmentService = UContainer.Resolve<IAttachmentService>();
                oIAttachmentService.Initialize(DBHelperString);
                AttachmentModel model = oIAttachmentService.GetAttachmentModelByAttachmentID(attachmentID);

                if (model != null)
                {
                    byte[] attachContent = model.AttachmentContent;
                    if (attachContent != null && attachContent.Length > 0)
                    {
                        context.Response.Clear();
                        context.Response.Charset = "gb2312";
                        context.Response.Buffer = false;
                        context.Response.AddHeader("Content-Length", attachContent.Length.ToString());
                        context.Response.AddHeader("Content-Disposition", 
                            string.Concat("attachment;filename=", HttpUtility.UrlEncode(model.AttachmentName, System.Text.Encoding.UTF8)));
                        context.Response.ContentType = "application/pdf";
                        context.Response.BinaryWrite(attachContent);
                        context.Response.Flush();
                        context.Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Clear();
                context.Response.Write(ex.Message);
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}